package com.lifl.ecogarde;

import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.net.http.AndroidHttpClient;
import android.util.Log;

public class Browser implements Serializable {
	
	private static final long serialVersionUID = 1360904286637486652L;
	private final String TAG = "Browser";
	public final static String USER_AGENT = "Android";// "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142 Safari/535.19";
	public final static long GRACE_TIME = 0; // Dure d'inactivit minimale entre 2 requetes

	protected AndroidHttpClient client;
	protected HttpContext clientContext;
	protected CookieStore cookieStore;
	protected BlockingQueue<HttpUriRequest> taskQueue = new ArrayBlockingQueue<HttpUriRequest>(
			1);
	protected long timestampOfLastResponse;
     
    public Browser() {
    	    
            this.client = AndroidHttpClient.newInstance(USER_AGENT); // Le "navigateur" qui va scrapper
            this.clientContext = new BasicHttpContext(); //  c'est pour avoir un "navigateur" plus réaliste
            this.cookieStore = new BasicCookieStore();
            this.clientContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // en l'occurence, pour garder les cookies            
            this.timestampOfLastResponse = 0;
    }
     
    protected long getGraceDuration() {
         return GRACE_TIME - (System.currentTimeMillis()-timestampOfLastResponse);
    }
     
    public HttpContext getContext(){
    	 return clientContext;
    }

	public void setContext(HttpContext context) {
		clientContext = context;
	}	
     
	public HttpResponse execute(HttpUriRequest request) {
		try {
			this.taskQueue.put(request); // Si une requete est déjà en cours,
											// celle-ci sera bloque
			AndroidHttpClient.modifyRequestToAcceptGzipResponse(request);

			long graceDuration = getGraceDuration();
			if (graceDuration > 0) {
				Log.i(TAG, String.format("sleep (%d ms)" + graceDuration));
				Thread.sleep(graceDuration); // On fait respecter le délai
												// d'inactivité
				Log.i(TAG, "wake-up");
			}
			
			
			HttpResponse result = this.client.execute(request, clientContext);
			
			CookieStore cs = (CookieStore) clientContext.getAttribute(ClientContext.COOKIE_STORE);

			for (int i = 0; i < cs.getCookies().size(); i++) {

				Log.d(TAG, "@@@@@@@@@@@@@@@@@   Cookies get from the Browser Context: " + cs.getCookies().get(i));
			}
	        
			this.timestampOfLastResponse = System.currentTimeMillis(); // On rarme le délai de grace
			this.taskQueue.take(); // On ouvre la cage
			return result;
		} catch (Exception e) {
			Log.e(TAG, "error execute");
		}

		return null;
	}
}
